package com.example.lottery.config;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * -- Created by IntelliJ IDEA.
 * -- REMARK:  统一请求报文输出、执行时间监控
 * -- User: tan.wei
 * -- Date: 2020/12/21
 * -- Time: 1:19 下午
 * --
 */

@Slf4j
@Aspect
@Component
public class ResponseLogAspect {

    @Resource
    private HttpServletRequest request;

    /**
     * 匹配controller层的方法
     */
    @Pointcut(value = "(execution(public * com.example.lottery.controller..*.*(..)))")
    private void controllerPointcut() {
    }

    @Around(value = "controllerPointcut()")
    public Object process(ProceedingJoinPoint point) throws Throwable {
        String requestUri = Objects.requireNonNull(request).getRequestURI();
        String requestMethod = request.getMethod();
        // 构建成一条长 日志，避免并发下日志错乱k
        StringBuilder beforeReqLog = new StringBuilder(300);
        // 日志参数
        List<Object> beforeReqArgs = new ArrayList<>();
        beforeReqLog.append("\n\n================  Request Start  ================\n");
        // 打印路由
        beforeReqLog.append("===> {}: {}");
        beforeReqArgs.add(requestMethod);
        beforeReqArgs.add(requestUri);
        Map<String, Object> paraMap = getNameAndValue(point);
        // 请求参数
        if (paraMap.isEmpty()) {
            beforeReqLog.append("\n");
        } else {
            beforeReqLog.append("\n");
            beforeReqLog.append("===>Parameters: {}\n");
            beforeReqArgs.add(JSONObject.toJSON(paraMap));
        }
        // 打印请求头
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = headers.nextElement();
            String headerValue = request.getHeader(headerName);
            beforeReqLog.append("===Headers===  {} : {}\n");
            beforeReqArgs.add(headerName);
            beforeReqArgs.add(headerValue);
        }
        beforeReqLog.append("================  Request  End   ================\n");
        // 打印执行时间
        long startNs = System.nanoTime();
        log.info(beforeReqLog.toString(), beforeReqArgs.toArray());
        // aop 执行后的日志
        StringBuilder afterReqLog = new StringBuilder(200);
        // 日志参数
        List<Object> afterReqArgs = new ArrayList<>();
        afterReqLog.append("\n\n================  Response Start  ===============\n");
        try {
            Object result = point.proceed();
//            // 打印返回结构体
            afterReqLog.append("===Result===  {}\n");
            afterReqArgs.add(JSONObject.toJSON(result));
            return result;
        } finally {
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            afterReqLog.append("<=== {}: {} ({} ms)\n");
            afterReqArgs.add(requestMethod);
            afterReqArgs.add(requestUri);
            afterReqArgs.add(tookMs);
            afterReqLog.append("================  Response  End   ===============\n");
            log.info(afterReqLog.toString(), afterReqArgs.toArray());
        }
    }

    /**
     * 获取参数Map集合
     */
    private Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
        Map<String, Object> param = new HashMap<>(8);

        Object[] paramValues = joinPoint.getArgs();
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();

        for (int i = 0; i < paramNames.length; i++) {
            if (paramValues[i] instanceof ServletRequest || paramValues[i] instanceof ServletResponse
                    || paramValues[i] instanceof MultipartFile) {
				/* ServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException: It is
				illegal to call this method if the current request is not in asynchronous
				mode (i.e. isAsyncStarted() returns false)
				ServletResponse不能序列化 从入参里排除，否则报异常：java.lang.IllegalStateException:
				getOutputStream() has already been called for this response*/
                continue;
            }
            param.put(paramNames[i], paramValues[i]);
        }
        if (log.isDebugEnabled()) {
            log.debug("param: {}", JSONObject.toJSONString(param));
        }
        return param;
    }


    public String format(Object result) {
        try {
            Object json = JSONObject.toJSON(result);
            if (Objects.isNull(json)) return null;
            ByteArrayInputStream in = new ByteArrayInputStream(json.toString().getBytes());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            char ch;
            int read;
            int space = 0;
            while ((read = in.read()) > 0) {
                ch = (char) read;
                switch (ch) {
                    case '{': {
                        space = outputAndRightMove(space, ch, out);
                        break;
                    }
                    case '[': {
                        out.write(ch);
                        space += 2;
                        break;
                    }
                    case '}': {
                        space = outputAndLeftMove(space, ch, out);
                        break;
                    }
                    case ']': {
                        space = outputAndLeftMove(space, ch, out);
                        break;
                    }
                    case ',': {
                        out.write(ch);
                        outputNewline(out);
                        out.write(getBlankingStringBytes(space));
                        break;
                    }
                    default: {
                        out.write(ch);
                        break;
                    }
                }
            }
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public int outputAndRightMove(int space, char ch, ByteArrayOutputStream out) throws IOException {
        //换行
        outputNewline(out);
        //向右缩进
        out.write(getBlankingStringBytes(space));
        out.write(ch);
        outputNewline(out);
        space += 2;
        //再向右缩进多两个字符
        out.write(getBlankingStringBytes(space));
        return space;
    }

    public int outputAndLeftMove(int space, char ch, ByteArrayOutputStream out) throws IOException {
        outputNewline(out);
        space -= 2;
        out.write(getBlankingStringBytes(space));
        out.write(ch);
        return space;
    }

    public byte[] getBlankingStringBytes(int space) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < space; i++) {
            sb.append(" ");
        }
        return sb.toString().getBytes();
    }

    public void outputNewline(ByteArrayOutputStream out) {
        out.write('\n');
    }
}
